package cn.com.hbhgkj.webapp.action;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.AccessDeniedException;

import cn.com.hbhgkj.Constants;
import cn.com.hbhgkj.ReviewCode;
import cn.com.hbhgkj.dao.SearchException;
import cn.com.hbhgkj.model.CopyrightApplication;
import cn.com.hbhgkj.model.LabelValue;
import cn.com.hbhgkj.service.CopyrightApplicationManager;
import cn.com.hbhgkj.util.DateUtil;

import com.opensymphony.xwork2.Preparable;

public class CopyrightApplicationAction extends BaseAction implements
		Preparable {
	private CopyrightApplicationManager copyrightApplicationManager;
	private List copyrightApplications;
	private CopyrightApplication copyrightApplication;
	private Long id;
	private String query;

	public void setCopyrightApplicationManager(
			CopyrightApplicationManager copyrightApplicationManager) {
		this.copyrightApplicationManager = copyrightApplicationManager;
	}

	public List getCopyrightApplications() {
		return copyrightApplications;
	}

	/**
	 * Grab the entity from the database before populating with request
	 * parameters
	 */
	public void prepare() {
		if (getRequest().getMethod().equalsIgnoreCase("post")) {
			// prevent failures on new
			String copyrightApplicationId = getRequest().getParameter(
					"copyrightApplication.id");
			if (copyrightApplicationId != null
					&& !copyrightApplicationId.equals("")) {
				copyrightApplication = copyrightApplicationManager
						.get(new Long(copyrightApplicationId));
			}
		}
	}

	public void setQ(String q) {
		this.query = q;
	}

	public String getQuery() {
		return query;
	}

	public String list() {
		try {
			if (administrator()) {
				copyrightApplications = copyrightApplicationManager
						.search(query);
			} else {
				copyrightApplications = copyrightApplicationManager
						.findByApplicant(getCurrentUser());
			}
		} catch (SearchException se) {
			addActionError(se.getMessage());
			copyrightApplications = copyrightApplicationManager.getAll();
		}
		return SUCCESS;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public CopyrightApplication getCopyrightApplication() {
		return copyrightApplication;
	}

	public void setCopyrightApplication(
			CopyrightApplication copyrightApplication) {
		this.copyrightApplication = copyrightApplication;
	}

	public String delete() {
		copyrightApplicationManager.remove(copyrightApplication.getId());
		saveMessage(getText("copyrightApplication.deleted"));

		return SUCCESS;
	}

	public String edit() {
		if (id != null) {
			copyrightApplication = copyrightApplicationManager.get(id);
		} else {
			copyrightApplication = new CopyrightApplication();
			copyrightApplication.setSqrname(getCurrentUser().getCompanyName());
			copyrightApplication.setSqraddress(getCurrentUser().getAddress()
					.getAddress());
			copyrightApplication.setSqrpostCode(getCurrentUser().getAddress()
					.getPostalCode());
			copyrightApplication.setSqrcontactPerson(getCurrentUser()
					.getContact());
			copyrightApplication.setSqrphone(getCurrentUser()
					.getContactNumber());
			copyrightApplication.setSqremail(getCurrentUser().getEmail());
			copyrightApplication
					.setSqrmobile(getCurrentUser().getPhoneNumber());
			copyrightApplication.setSqrfax(getCurrentUser().getFax());
		}

		return SUCCESS;
	}

	public String save() throws Exception {
		if (cancel != null) {
			return "cancel";
		}

		if (delete != null) {
			return delete();
		}

		boolean isNew = (copyrightApplication.getId() == null);

		if (isNew) {
			copyrightApplication.setApplicant(getCurrentUser());
			copyrightApplication.setApplyTime(new Date());
			copyrightApplication.setLoginId(Constants.AGENT_USERNAME);

		}
		copyrightApplication.setUpdateTime(new Date());
		copyrightApplication.setState(ReviewCode.PENDING_REVIEW.getValue());
		copyrightApplicationManager.save(copyrightApplication);

		String key = (isNew) ? "copyrightApplication.added"
				: "copyrightApplication.updated";
		saveMessage(getText(key));

		if (!isNew) {
			return INPUT;
		} else {
			return SUCCESS;
		}
	}

	// method of ADMIN role
	public String approve() {
		// validate current user
		if (!administrator()) {
			throw new AccessDeniedException(
					"Access Denied: Only administrators are allowed to review.");
		}
		try {
			copyrightApplicationManager.review(this.getCurrentUser(),
					copyrightApplication, ReviewCode.PASS);
		} catch (Exception e) {
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	public String refuse() {
		// validate current user
		if (!administrator()) {
			throw new AccessDeniedException(
					"Access Denied: Only administrators are allowed to review.");
		}
		try {
			copyrightApplicationManager.review(this.getCurrentUser(),
					copyrightApplication, ReviewCode.FAIL);
		} catch (Exception e) {
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	private List<LabelValue> mutilDocList = new ArrayList<LabelValue>();
	private List<LabelValue> exceptionalRepositList = new ArrayList<LabelValue>();
	private List<LabelValue> peopleTypeList = new ArrayList<LabelValue>();

	private List<LabelValue> hasLetterList = new ArrayList<LabelValue>();

	public synchronized List<LabelValue> getHasLetterList() {
		if (hasLetterList.size() == 0) {
			hasLetterList.add(new LabelValue(
					getText("copyrightApplication.hasLetter.no"), ""));
			hasLetterList.add(new LabelValue(
					getText("copyrightApplication.hasLetter.yes"), "是"));
		}
		return hasLetterList;
	}

	public synchronized List<LabelValue> getPeopleTypeList() {
		if (peopleTypeList.size() == 0) {
			peopleTypeList = new ArrayList<LabelValue>();
			peopleTypeList.add(new LabelValue(
					getText("copyrightApplication.peopleType.1"), "1"));
			peopleTypeList.add(new LabelValue(
					getText("copyrightApplication.peopleType.21"), "21"));
			peopleTypeList.add(new LabelValue(
					getText("copyrightApplication.peopleType.22"), "22"));
			peopleTypeList.add(new LabelValue(
					getText("copyrightApplication.peopleType.23"), "23"));
			peopleTypeList.add(new LabelValue(
					getText("copyrightApplication.peopleType.24"), "24"));
			peopleTypeList.add(new LabelValue(
					getText("copyrightApplication.peopleType.3"), "3"));
			peopleTypeList.add(new LabelValue(
					getText("copyrightApplication.peopleType.4"), "4"));
		}
		return peopleTypeList;
	}

	public synchronized List<LabelValue> getExceptionalRepositList() {
		if (exceptionalRepositList.size() == 0) {
			exceptionalRepositList = new ArrayList<LabelValue>();
			exceptionalRepositList
					.add(new LabelValue(
							getText("copyrightApplication.difmatReferMode.exception.1"),
							"exp1"));
			exceptionalRepositList
					.add(new LabelValue(
							getText("copyrightApplication.difmatReferMode.exception.2"),
							"exp2"));
			exceptionalRepositList
					.add(new LabelValue(
							getText("copyrightApplication.difmatReferMode.exception.3"),
							"exp3"));
		}
		return exceptionalRepositList;
	}

	public synchronized List<LabelValue> getMutilDocList() {
		if (mutilDocList.size() == 0) {
			mutilDocList = new ArrayList<LabelValue>();
			mutilDocList
					.add(new LabelValue(
							getText("copyrightApplication.isMutilDoc.oneDoc"),
							"oneDoc"));
			mutilDocList.add(new LabelValue(
					getText("copyrightApplication.isMutilDoc.MultiDoc"),
					"mutilDoc"));
		}
		return mutilDocList;
	}

	@Override
	public void validate() {
		super.validate();

		if (StringUtils.isEmpty(copyrightApplication.getCompleteDate())) {
			this.addActionError(getText(
					"errors.requiredField",
					new String[] { getText("copyrightApplication.completeDate") }));
		} else {

			try {
				if (DateUtil.convertStringToDate("yyyy-MM-dd",
						copyrightApplication.getCompleteDate()).after(
						new Date())) {
					this.addActionError(getText(
							"errors.lessThanNow",
							new String[] { getText("copyrightApplication.completeDate") }));
				}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (!StringUtils.isEmpty(copyrightApplication.getPublishStatus())
				&& copyrightApplication.getPublishStatus().equals("1")) {
			if (StringUtils.isEmpty(copyrightApplication.getAppearDate())) {
				this.addActionError(getText(
						"errors.requiredField",
						new String[] { getText("copyrightApplication.appearDate") }));
			} else {
				try {
					if (DateUtil.convertStringToDate("yyyy-MM-dd",
							copyrightApplication.getAppearDate()).after(
							new Date())) {
						this.addActionError(getText(
								"errors.lessThanNow",
								new String[] { getText("copyrightApplication.appearDate") }));
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (copyrightApplication.getAppearDate().compareTo(
						copyrightApplication.getCompleteDate()) <= 0) {
					this.addActionError(getText(
							"errors.greatThan",
							new String[] {
									getText("copyrightApplication.appearDate"),
									getText("copyrightApplication.completeDate") }));

				}


				if (StringUtils.isEmpty(copyrightApplication
						.getAppearAreaCity())) {
					this.addActionError(getText(
							"errors.requiredField",
							new String[] { getText("copyrightApplication.appearAreaCity") }));
				} else {
					if (copyrightApplication.getAppearAreaCity().length() > 40) {
						this.addActionError("首次发表城市 不能大于 40 个字符。");
						/*this.addActionError(getText(
								"errors.maxlength",
								new String[] {
										getText("copyrightApplication.appearAreaCity"),
										"40" }));*/
					}
				}
			}

		}

		for (String each : _names) {
			if (StringUtils.isEmpty(each)) {
				this.addActionError(getText(
						"errors.requiredField",
						new String[] { getText("copyrightApplication.label.copyrighterName") }));
				break;
			}

			if (each.length() > 100) {
				this.addActionError(getText("errors.maxlength", new String[] {
						getText("copyrightApplication.label.copyrighterName"),
						"100" }));
				break;
			}
		}

		for (String each : _citys) {
			if (StringUtils.isEmpty(each)) {
				this.addActionError(getText("errors.requiredField",
						new String[] { getText("copyrightApplication.city1") }));
				break;
			}
		}

		for (String each : _idNumbers) {
			if (StringUtils.isEmpty(each)) {
				this.addActionError(getText(
						"errors.requiredField",
						new String[] { getText("copyrightApplication.idNumber1") }));
				break;
			}
		}

		for (String each : _busTypes) {
			if (StringUtils.isEmpty(each)) {
				this.addActionError(getText(
						"errors.requiredField",
						new String[] { getText("copyrightApplication.busType1") }));
				break;
			}
		}

	}

	private String[] _names;
	private String[] _citys;
	private String[] _idNumbers;
	private String[] _busTypes;

	public String[] get_names() {
		return _names;
	}

	public void set_names(String[] _names) {
		this._names = _names;
	}

	public String[] get_citys() {
		return _citys;
	}

	public void set_citys(String[] _citys) {
		this._citys = _citys;
	}

	public String[] get_idNumbers() {
		return _idNumbers;
	}

	public void set_idNumbers(String[] _idNumbers) {
		this._idNumbers = _idNumbers;
	}

	public String[] get_busTypes() {
		return _busTypes;
	}

	public void set_busTypes(String[] _busTypes) {
		this._busTypes = _busTypes;
	}

}